from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponse
from .forms import MyForm,RegisterForm
from .models import User
# Create your views here.

class IndexView(View):
    def get(self,request):
        form = MyForm()
        return render(request,'index.html',context={'form':form})
    def post(self,request):
        form = MyForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data.get('telephone')
            return HttpResponse("CHENGGONG")
        else:
            print(form.errors.get_json_data())
            return HttpResponse("失败")

class RegisterView(View):
    def get(self,request):
        form = RegisterForm()
        return render(request,'register.html',context={'form':form})
    def post(self,request):
        form = RegisterForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            telephone = form.cleaned_data.get('telephone')
            User.objects.create(username=username,telephone=telephone)
            return HttpResponse("注册成功")
        else:
            # print(form.errors.get_json_data()){'telephone': [{'message': '18888888888 已经被注册', 'code': ''}]}
            # print(form.errors)<ul class="errorlist"><li>telephone<ul class="errorlist"><li>18888888888 已经被注册</li></ul></li></ul>
            #print(form.errors.as_json())
            #{"telephone": [{"message": "18888888888 \u5df2\u7ecf\u88ab\u6ce8\u518c", "code": ""}]}
            # errors = form.get_errors()
            #{'username': [{'message': '请输入邮箱类型', 'code': 'invalid'}], 'telephone': [{'message': '请输入正确格式的手机号', 'code': 'invalid'}], '__all__': [{'message': '两次密码不一致', 'code': ''}]}
            #print(form.errors.get_json_data())
            errors = form.get_errors()
            # return HttpResponse("注册失败")
            print(errors)
            return HttpResponse("KO")